package com.ojoin.trade.supplyloan_core.web.service.impl;

import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.SMSSendUtil;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.web.dao.BaseDao;
import com.ojoin.trade.common.web.domain.NotificationTemplate;
import com.ojoin.trade.common.web.service.TbUploadFileService;
import com.ojoin.trade.common.web.service.impl.BaseServiceImpl;
import com.ojoin.trade.common.web.service.impl.NotificationTemplateService;
import com.ojoin.trade.common_core.web.service.impl.DataVersionValidationService;
import com.ojoin.trade.supplyloan_core.constdef.ISLConstDef;
import com.ojoin.trade.supplyloan_core.web.dao.TbSlLoanCreditDao;
import com.ojoin.trade.supplyloan_core.web.domain.*;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanCreditService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanFloatService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanInfoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlProcessInfoService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 15-10-28
 * Time: 上午10:47
 * To change this template use File | Settings | File Templates.
 */
@Service
public class TbSlLoanCreditServiceImpl extends BaseServiceImpl<TbSlLoanCreditLog> implements TbSlLoanCreditService {

    @Autowired
    protected TbSlLoanCreditDao dao;

    @Autowired
    private DataVersionValidationService validationService;

    @Autowired
    private TbSlLoanInfoService   tbSlLoanInfoService;
    @Autowired
    private TbSlLoanFloatService tbSlLoanFloatService;

    @Autowired
    private TbUploadFileService uploadService;

    @Autowired
    private TbSlProcessInfoService tbSlProcessInfoService;

    @Autowired
    private NotificationTemplateService notificationTemplateService;
    
    private Logger loger= LoggerFactory.getLogger(TbSlLoanCreditServiceImpl.class);

    @Override
    protected BaseDao<TbSlLoanCreditLog> getBaseDao() {
        return dao;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void insertTbSlLoanCreditLog(TbSlLoanCreditLog logvo) throws BusinessException {
        ((TbSlLoanCreditDao)this.getBaseDao()).insertTbSlLoanCredit(logvo);
    }

    @Override
    public int updateTbSlLoanCredit(Map<String, Object> parammap) throws BusinessException {
       return ((TbSlLoanCreditDao)this.getBaseDao()).updateTbSlLoanCredit(parammap);
    }

    @Override
    public List<TbSlLoanCreditLog> queryNotPayBackCreditLogByJoinid(int joinid,Pageable page) throws BusinessException {
        return   ((TbSlLoanCreditDao)this.getBaseDao()).queryNotPayBackCreditLogByJoinid(joinid, page);
    }

    @Override
    public List<TbSlLoanCreditLog> queryNotPayBackCreditLogByJoinidNotPage(int joinid) throws BusinessException {
        return   ((TbSlLoanCreditDao)this.getBaseDao()).queryNotPayBackCreditLogByJoinidNotpage(joinid);
    }

    @Override
    public List<TbSlLoanCreditLogVo> queryAllNotPayBackCreditLog(int userIdOfJoinOfCreditor) throws BusinessException {
        return  ((TbSlLoanCreditDao)this.getBaseDao()).queryAllNotPayBackCreditLog(userIdOfJoinOfCreditor);
    }

    @Override
    public void updateBatchTbSlLoanCredit(List<TbSlLoanCreditLog> list) throws BusinessException {

        this.getBaseDao().updateInBatch(list);


    }

    @Override
    public List<TbSlStatusCreditLogVo> queryCreditLogByStatus(int status,int userIdOfJoinOfCreditor, Pageable page) throws BusinessException {

        return  ((TbSlLoanCreditDao)this.getBaseDao()).queryCreditLogByStatus(status, userIdOfJoinOfCreditor, page);

    }

    @Override
    public TbSlLoanCreditLog queryCreditLogById(int id) throws BusinessException {

        return  ((TbSlLoanCreditDao)this.getBaseDao()).queryCreditLogById(id);
    }

    @Override
    public String querySumApplyLoanByJoinid(int id) throws BusinessException {

        return ((TbSlLoanCreditDao)this.getBaseDao()).querySumApplyLoanByJoinid(id);

    }

    /**
     *
     *
     *
     * @throws BusinessException
     */
    @Override
    public void updateCaculateCreditFee() throws BusinessException {
        try{
               updateCreditFee();
        }catch (Exception e){
            throw new BusinessException("计息失败",e);
        }
    }
   private void updateCreditFee()throws Exception{

          List<TbSlLoanCreditLog> list=((TbSlLoanCreditDao)this.getBaseDao()).queryNotPayBack();
          if(CommonUtils.isEmpty(list)){
              return;
          }
          List<TbSlLoanCreditLog> updatelist=new ArrayList<>();
          for(TbSlLoanCreditLog log:list){
              if(log.getCalculateDate()!=null&&log.getCalculateDate().equals(TimeUtils.getCurDate())){
                  continue;
              }
              TbSlCalculateFeeVO vo=new TbSlCalculateFeeVO();
              long totalnotpayamount=CommonUtils.getLong(log.getTotalNotPaybackAmount());
              String lastrefundtime=log.getLastRefundTime();

                  String fee=log.getFee();
                 if(CommonUtils.isEmpty(fee)){
                  fee="0";
                 }
                  String rate=log.getRate();
                 if(CommonUtils.isEmpty(rate)){
                  rate="0";
                 }
                  String enddate=TimeUtils.getCurDate();
                  if(enddate.compareTo(lastrefundtime)>0){
                      enddate=lastrefundtime;
                  }
                  //如果该笔贷款已经超过了正常的还款期，则结束日当天也要计基础利息，因此天数+1
                  long days = TimeUtils.getDateSpaceOfDay(log.getRealLoanTime(),enddate);
                   if(TimeUtils.getCurDate().compareTo(lastrefundtime)>0){
                      days=days+1;
                   }
                      double amountdouble=new Double(totalnotpayamount);
                      BigDecimal feedecimal=new BigDecimal(amountdouble).multiply(new BigDecimal(fee).divide(new BigDecimal(100))).multiply(new BigDecimal(days));
                      long feelong=feedecimal.setScale(0,BigDecimal.ROUND_HALF_UP).longValue();
                      log.setTotalNotPaybackFeeOld(new Long(feelong).toString());
                      log.setTotalNotPaybackFee(new Long(feelong).toString());
                      BigDecimal ratedecimal=new BigDecimal(amountdouble).multiply(new BigDecimal(rate).divide(new BigDecimal(100))).multiply(new BigDecimal(days));
                      long ratelong=ratedecimal.setScale(0,BigDecimal.ROUND_HALF_UP).longValue();
                      log.setTotalNotPaybackRateOld(new Long(ratelong).toString());
                      log.setTotalNotPaybackRate(new Long(ratelong).toString());
                    log.setCalculateDate(TimeUtils.getCurDate());
              if(TimeUtils.getCurDate().compareTo(lastrefundtime)>0)
              {
                  String reneweddate=log.getRenewedRefundTime();
                  String renewwdbegindate=log.getRenewedBeginTime();
                  if("Y".equals(log.getRenewedStatus())){
                      String renewedfee=log.getRenewedFee();
                      if(CommonUtils.isEmpty(renewedfee)){
                          renewedfee="0";
                      }
                      String renewedratio=log.getRenewedRate();
                      if(CommonUtils.isEmpty(renewedratio)){
                          renewedratio="0";
                      }
                      String renewedenddate=TimeUtils.getCurDate();
                      if(reneweddate.compareTo(renewedenddate)<0){
                          renewedenddate=log.getRenewedRefundTime();
                      }
                      long reneweddays=TimeUtils.getDateSpaceOfDay(renewwdbegindate,renewedenddate);
                      if(reneweddate.compareTo(TimeUtils.getCurDate())<0){
                          reneweddays=reneweddays+1;
                      }
                      vo.setRenewedDays(reneweddays);
                       BigDecimal renewedfeedecimal=new BigDecimal(amountdouble).multiply(new BigDecimal(renewedfee).divide(new BigDecimal(100))).multiply(new BigDecimal(reneweddays));
                      long renewedfeelong=renewedfeedecimal.setScale(0,BigDecimal.ROUND_HALF_UP).longValue();
                      log.setTotalNotPaybackRenewedFee(new Long(renewedfeelong).toString());
                           log.setTotalNotPaybackRenewedFeeOld(new Long(renewedfeelong).toString());
                           BigDecimal renewedratedecimal=new BigDecimal(amountdouble).multiply(new BigDecimal(renewedratio).divide(new BigDecimal(100))).multiply(new BigDecimal(reneweddays));
                           long renewedratelong=renewedratedecimal.setScale(0,BigDecimal.ROUND_HALF_UP).longValue();
                           log.setTotalNotPaybackRenewedRate(new Long(renewedratelong).toString());
                           log.setTotalNotPaybackRenewedRateOld(new Long(renewedratelong).toString());
                      if(reneweddate.compareTo(TimeUtils.getCurDate())<0){
                          String penty=log.getPenalty();
                          if(CommonUtils.isEmpty(penty)){
                              penty="0";
                          }
                          BigDecimal pentyratedecimal=(new BigDecimal(fee).add(new BigDecimal(rate))).multiply(new BigDecimal(1).add(new BigDecimal(penty).divide(new BigDecimal(100))));
                          long pentydays= TimeUtils.getDateSpaceOfDay(reneweddate,TimeUtils.getCurDate())-1;
                          BigDecimal pentydecimal= new BigDecimal(amountdouble).multiply(pentyratedecimal.divide(new BigDecimal(100))).multiply(new BigDecimal(pentydays));
                          long pentylong=pentydecimal.setScale(0,BigDecimal.ROUND_HALF_UP).longValue();
                          log.setTotalNotPaybackPenalty(new Long(pentylong).toString());
                          log.setTotalNotPaybackPenaltyOld(new Long(pentylong).toString());

                      }
                  }else if(CommonUtils.isEmpty(log.getRenewedStatus())||"N".equals(log.getRenewedStatus())||"R".equals(log.getRenewedStatus())){
                      String penty=log.getPenalty();
                      if(CommonUtils.isEmpty(penty)){
                          penty="0";
                      }
                      BigDecimal pentyratedecimal=(new BigDecimal(fee).add(new BigDecimal(rate))).divide(new BigDecimal(100)).multiply(new BigDecimal(1).add(new BigDecimal(penty).divide(new BigDecimal(100))));
                      vo.setPenaltyRate(pentyratedecimal.toString());
                      long pentydays= TimeUtils.getDateSpaceOfDay(lastrefundtime,TimeUtils.getCurDate())-1;
                      vo.setPenaltyDays(pentydays);
                     BigDecimal pentydecimal= new BigDecimal(amountdouble).multiply(pentyratedecimal).multiply(new BigDecimal(pentydays));
                      long pentylong=pentydecimal.setScale(0,BigDecimal.ROUND_HALF_UP).longValue();
                      log.setTotalNotPaybackPenalty(new Long(pentylong).toString());
                      log.setTotalNotPaybackPenaltyOld(new Long(pentylong).toString());
                  }
              }
              calculateFloat(log);

              vo.setCode(log.getCode());
              vo.setFee(log.getFee());
              vo.setRate(log.getRate());
              vo.setNormalDays(days);
              vo.setNormalFeeAmount(log.getTotalNotPaybackFee());
              vo.setNormalRateAmount(log.getTotalNotPaybackRate());
              vo.setRenewedFeeAmount(log.getTotalNotPaybackRenewedFee());
              vo.setRenewedRateAmount(log.getTotalNotPaybackRenewedRate());
              vo.setPenaltyAmount(log.getTotalNotPaybackPenalty());
              vo.setNormalFeeAmountOld(log.getTotalNotPaybackFeeOld());
              vo.setNormalRateAmountOld(log.getTotalNotPaybackRateOld());
              vo.setRenewedFeeAmountOld(log.getTotalNotPaybackRenewedFeeOld());
              vo.setRenewedRateAmountOld(log.getTotalNotPaybackRenewedRateOld());
              vo.setPenaltyAmountOld(log.getTotalNotPaybackPenaltyOld());
              LogUtils.info(LogUtils.getSlloanLog(),vo.toString());
              updatelist.add(log);
   }
       ((TbSlLoanCreditDao)this.getBaseDao()).updateInBatch(updatelist);
   }

   private void calculateFloat(TbSlLoanCreditLog log)throws BusinessException{
       List<TbSlLoanFloat> list=tbSlLoanFloatService.queryFloatVoByCreditId(log.getId());
       if(CommonUtils.isEmpty(list)){
           return;
       }
       BigDecimal totalfee=new BigDecimal("0");
       if(!CommonUtils.isEmpty(log.getTotalNotPaybackFee())){
           totalfee= new BigDecimal(log.getTotalNotPaybackFee());
       }
       BigDecimal totalrate=new BigDecimal("0");
       if(!CommonUtils.isEmpty(log.getTotalNotPaybackRate())){
           totalrate=new BigDecimal(log.getTotalNotPaybackRate());
       }
       BigDecimal renewedfee=new BigDecimal("0");
       if(!CommonUtils.isEmpty(log.getTotalNotPaybackRenewedFee())){
           renewedfee=new BigDecimal(log.getTotalNotPaybackRenewedFee());
       }
       BigDecimal renewedrate=new BigDecimal("0");
       if(!CommonUtils.isEmpty(log.getTotalNotPaybackRenewedRate())){
           renewedrate=new BigDecimal(log.getTotalNotPaybackRenewedRate());
       }
       BigDecimal penalty=new BigDecimal("0");
       if(!CommonUtils.isEmpty(log.getTotalNotPaybackPenalty())){
           penalty=new BigDecimal(log.getTotalNotPaybackPenalty());
       }
       for(TbSlLoanFloat floatvo:list){
           String type=floatvo.getType();
           if(ISLConstDef.FLOAT_TYPE_RATE.equals(type)){
               totalrate=totalrate.add(new BigDecimal(floatvo.getAmount()));
               if(totalrate.doubleValue()<0){
                   throw new BusinessException("调差额的金额不能大于欠款额");
               }
               continue;

           }
           if(ISLConstDef.FLOAT_TYPE_FEE.equals(type)){
              totalfee=totalfee.add(new BigDecimal(floatvo.getAmount()));
               if(totalfee.doubleValue()<0){
                   throw new BusinessException("调差额的金额不能大于欠款额");
               }
                           continue;
           }
           if(ISLConstDef.FlOAT_TYPE_RENEWEDFEE.equals(type)){
               renewedfee=renewedfee.add(new BigDecimal(floatvo.getAmount()));
               if(renewedfee.doubleValue()<0){
                   throw new BusinessException("调差额的金额不能大于欠款额");
               }
               continue;
           }
           if(ISLConstDef.FLOAT_TYPE_RENEWEDRATE.equals(type)){
               renewedrate=renewedrate.add(new BigDecimal(floatvo.getAmount()));
               if(renewedrate.doubleValue()<0){
                   throw new BusinessException("调差额的金额不能大于欠款额");
               }
               continue;
           }
           if(ISLConstDef.FLOAT_TYPE_PENALTY.equals(type)){
                penalty=penalty.add(new BigDecimal(floatvo.getAmount()));
                if(penalty.doubleValue()<0){
                    throw new BusinessException("调差额的金额不能大于欠款额");
                }
               continue;
           }
       }
       log.setTotalNotPaybackRate(totalrate.toString());
       log.setTotalNotPaybackFee(totalfee.toString());
       log.setTotalNotPaybackRenewedRate(renewedrate.toString());
       log.setTotalNotPaybackRenewedFee(renewedfee.toString());
       log.setTotalNotPaybackPenalty(penalty.toString());

   }
   @Override
    public List<SlLoanTodoTaskVO> queryToDoTask(Pageable page) throws BusinessException {

        return ((TbSlLoanCreditDao)this.getBaseDao()).queryToDoTask(page);
    }

    @Override
    public void updateForRefuseLoan(String id, String memo) throws BusinessException {



    }

    @Override
    public List<TbSlLoanCreditLogVo> queryPayBackCreditLogByCause(Map map, Pageable page) throws BusinessException {
        return ((TbSlLoanCreditDao)this.getBaseDao()).queryPayBackCreditLogByCause(map, page);
    }

    @Override
    public List<TbSlLoanCreditLog> queryPaybackByJoinid(int joinid, Pageable page) throws BusinessException {
        return  ((TbSlLoanCreditDao)this.getBaseDao()).queryPaybackByJoinid(joinid, page);
    }

    @Override
    public String selectCreditLoanCountByJoinid(int joinuserid) throws BusinessException {
    	return  ((TbSlLoanCreditDao)this.getBaseDao()).selectCreditLoanCountByJoinid(joinuserid);
    }

    @Override
    public String selectNotcompleteCreditLoanByJoinid(int joinuserid) throws BusinessException {
    	return  ((TbSlLoanCreditDao)this.getBaseDao()).selectNotcompleteCreditLoanByJoinid(joinuserid);
    }
    
    @Override
    public List<TbSlLoanCreditLog> queryListByIds(List<Integer> idlist) throws BusinessException {
        return ((TbSlLoanCreditDao)this.getBaseDao()).queryCreditByIdList(idlist);
    }

    @Override
    public List<TbSlLoanCreditLog> queryApplyByJoinid(int joinid, Pageable page) throws BusinessException {
        return ((TbSlLoanCreditDao)this.getBaseDao()).queryApplyByJoinid(joinid, page);
    }

    public void deleteCreditLog(int id)throws BusinessException{
        this.deleteById(id);
    }

    @Override
    public void updateForCancelCreditLog() throws BusinessException {
        ((TbSlLoanCreditDao)this.getBaseDao()).cancelCredit();
    }
    private BigDecimal getRate(String fee,String initialrate)throws BusinessException{
        BigDecimal rate=new BigDecimal("0");
        if(!CommonUtils.isEmpty(fee)){
            rate=rate.add(new BigDecimal(fee));
        }
        if(!CommonUtils.isEmpty(rate)){
            rate=rate.add(new BigDecimal(initialrate));
        }
        return rate;
    }

    @Override
    public List<TbSlLoanCreditLog> queryCreditByJoinid(int joinid, Pageable page) throws BusinessException {

     List<TbSlLoanCreditLog> list=((TbSlLoanCreditDao)this.getBaseDao()).queryCreditByJoinid(joinid,page);
        if(!CommonUtils.isEmpty(list)){
            for(TbSlLoanCreditLog log:list){
                try{
                String refunddate=log.getLastRefundTime();
                long days=TimeUtils.getDateSpaceOfDay(TimeUtils.getCurDate(),refunddate);
                String curdate=TimeUtils.getCurDate();
                if(log.getCreditstatus().equals(IConstDef.LOAN_TYPE_OF_PAYALL)){
                    BigDecimal rate=getRate(log.getFee(),log.getRate());
                    log.setFee(rate.toString());
                    log.setCreditstatusTips("3");
                    continue;
                }
                if(curdate.compareTo(refunddate)<=0){
                BigDecimal rate=getRate(log.getFee(),log.getRate());
                log.setFee(rate.toString());
                log.setCreditstatusTips("0");
                }else{
                    String renewedddate=log.getRenewedRefundTime();
                    String renewedbegintime=log.getRenewedBeginTime();
                    if("Y".equals(log.getRenewedStatus())){
                        BigDecimal rate=getRate(log.getRenewedFee(),log.getRenewedRate());
                        BigDecimal jichurate=getRate(log.getFee(),log.getRate());
                        String ratetips;

                        log.setFee(rate.toString());
                        ratetips="基础日利率："+jichurate.toString()+"%;"+"展期日利率："+rate.toString()+"%";
                        String lastrefundtime=log.getLastRefundTime();
                        log.setLastRefundTime(log.getRenewedRefundTime());
                        log.setCreditstatusTips("1");
                        String totalNotPaybackRate=log.getTotalNotPaybackRate();
                        String totalNotPaybackRenewedRate=log.getTotalNotPaybackRenewedRate();
                        long totalNotPaybackRatelong=CommonUtils.getLong(totalNotPaybackRate);
                        long totalNotPaybackRenewedRatelong=CommonUtils.getLong(totalNotPaybackRenewedRate);
                        long totalnotpaybackrate=totalNotPaybackRatelong+totalNotPaybackRenewedRatelong;

                        BigDecimal totalnotpaybackratedecimal=new BigDecimal(totalNotPaybackRate).divide(new BigDecimal(100));
                        BigDecimal totalNotPaybackRenewedRatedecimal=new BigDecimal(totalNotPaybackRenewedRate).divide(new BigDecimal(100));
                        String intresttips="未还基础利息："+totalnotpaybackratedecimal.toString()+"元;未还展期利息："+totalNotPaybackRenewedRatedecimal.toString()+"元";
                        String refundtips="融资到期时间："+lastrefundtime+"；展期到期时间："+log.getRenewedRefundTime();
                        String realloantips="放款时间："+log.getRealLoanTime()+";展期时间："+log.getRenewedBeginTime();
                        String calculatetips="正常利息截止日："+lastrefundtime+";展期计息截止日："+log.getCalculateDate();
                        if(curdate.compareTo(renewedddate)>0){
                            String penalty=log.getPenalty();
                            if(CommonUtils.isEmpty(penalty)){
                                penalty="0";
                            }
                            BigDecimal penaltyrate=jichurate.multiply(new BigDecimal(1).add(new BigDecimal(penalty).divide(new BigDecimal(100))));
                            ratetips+=";罚息日利率："+penaltyrate.toString()+"%";
                            log.setCreditstatusTips("2");
                            log.setFee(penaltyrate.toString());
                            String totalNotPaybackPenalty=log.getTotalNotPaybackPenalty();
                            long totalNotPaybackPenaltylong=CommonUtils.getLong(totalNotPaybackPenalty);
                            BigDecimal totalNotPaybackPenaltyDecimal=new BigDecimal(totalNotPaybackPenalty).divide(new BigDecimal(100));
                            intresttips+="未还罚息："+totalNotPaybackPenaltyDecimal.toString()+"元";
                            totalnotpaybackrate+= totalNotPaybackPenaltylong;
                            calculatetips="正常利息截止日："+lastrefundtime+";展期计息截止日："+log.getRenewedRefundTime();
                        }
                        log.setTotalNotPaybackRate(new Long(totalnotpaybackrate).toString());
                        log.setInterestTips(intresttips);
                        log.setRefundTips(refundtips);
                        log.setRealloanTips(realloantips);
                        log.setCalculateTips(calculatetips);
                        log.setRateTips(ratetips);
                       }else{
                        BigDecimal jichurate=getRate(log.getFee(),log.getRate());
                        String penalty=log.getPenalty();
                        if(CommonUtils.isEmpty(penalty)){
                            penalty="0";
                        }
                        BigDecimal  rate=jichurate.multiply(new BigDecimal(1).add(new BigDecimal(penalty).divide(new BigDecimal(100))));
                        log.setRateTips("基础日利率："+jichurate.toString()+"%;罚息日利率："+rate.toString()+"%");
                        String totalNotPaybackRate=log.getTotalNotPaybackRate();
                        String totalNotPaybackRenewedRate=log.getTotalNotPaybackRenewedRate();
                        String totalNotPaybackPenalty=log.getTotalNotPaybackPenalty();
                       long totalNotPaybackRatelong=CommonUtils.getLong(totalNotPaybackRate);
                        BigDecimal totalNotPaybackRateDecimal=new BigDecimal(totalNotPaybackRate).divide(new BigDecimal(100));
                       long totalNotPaybackRenewedRatelong=CommonUtils.getLong(totalNotPaybackRenewedRate);
                        BigDecimal totalNotPaybackRenewedRateDecimal=new BigDecimal(totalNotPaybackRenewedRate).divide(new BigDecimal(100));
                       long totalNotPaybackPenaltylong=CommonUtils.getLong(totalNotPaybackPenalty);
                       BigDecimal totalNotPaybackPenaltyDecimal=new BigDecimal(totalNotPaybackPenalty).divide(new BigDecimal(100));
                        long totalnotpaybackrate=totalNotPaybackRatelong+totalNotPaybackRenewedRatelong+totalNotPaybackPenaltylong;
                        log.setTotalNotPaybackRate(new Long(totalnotpaybackrate).toString());
                         log.setCreditstatusTips("2");
                         log.setFee(rate.toString());
                        String interest="未还基础利息：" + totalNotPaybackRateDecimal.toString()+"元";
                        if(totalNotPaybackRenewedRatelong>0){
                            interest+=";未还展期利息：" +totalNotPaybackRenewedRateDecimal+"元";
                        }
                        if(totalNotPaybackPenaltylong>0){
                            interest+=";未还罚息："+totalNotPaybackPenaltyDecimal.toString()+"元";
                        }
                        log.setInterestTips(interest);
                        log.setRefundTips("融资到期时间："+refunddate);
                        log.setRealloanTips("放款时间："+log.getRealLoanTime());
                        log.setCalculateTips("正常利息截止日："+refunddate);

                    }
                }
                }catch (Exception e){
                    throw  new BusinessException("计算日期出错",e);
                }
            }

        }
        return list;
    }



    @Override
    public void updateBatchForFile(List<TbSlLoanCreditLog> list, String material) throws BusinessException {
        List<Integer> idlist=new ArrayList<>();
        for(TbSlLoanCreditLog logvo:list){

            lockById(logvo.getId());
            validationService.validateVO(logvo.getId(),"tb_sl_loan_credit_log",logvo.getRowUpdateTime());
            idlist.add(logvo.getId());
        }
        ((TbSlLoanCreditDao)this.getBaseDao()).batchUpdateFile(idlist,material);
        Map<String,Object> map=new HashMap<>();
        map.put("id",list.get(0).getProcessInfoId());
        map.put("loanStatus", IConstDef.LOAN_TYPE_OF_APPLICATION);
        tbSlProcessInfoService.updateTbSlProcessInfo(map);
        uploadService.updateStatusById(CommonUtils.getInt(material),IConstDef.UPLOADSTATUS_COMMITED);



    }

    @Override
    public TbSlNotPayBackCreditForFront queryNotPayback(int joinid,Pageable page) throws BusinessException {
       List<TbSlNotPayBackCredit> list=  ((TbSlLoanCreditDao)this.getBaseDao()).queryCreditNotPayBack(joinid,page);
        if(!CommonUtils.isEmpty(list)){
            for(TbSlNotPayBackCredit vo:list){

                BigDecimal rate=new BigDecimal("0");
                if(!CommonUtils.isEmpty(vo.getFee())){
                    rate=rate.add(new BigDecimal(vo.getFee()));
                }
                if(!CommonUtils.isEmpty(vo.getRate())){
                    rate=rate.add(new BigDecimal(vo.getRate()));
                }
                vo.setRate(rate.toString());
                if(TimeUtils.getCurDate().compareTo(vo.getLastRefundTime())<=0){
                    vo.setTotalNotPaybackRenewedAmount("0");
                }
            }
        }
      TbSlNotPayBackCreditForFront vo=new TbSlNotPayBackCreditForFront();
        vo.setListvo(list);
      TbSlLoanInfo loanInfo=tbSlLoanInfoService.queryTbSlLoanInfoByJoinid(joinid);
        vo.setLoanInfo(loanInfo);
        return vo;
    }

    @Override
    public void updateBatchCancel(List<Integer> idlist) throws BusinessException {

        ((TbSlLoanCreditDao)this.getBaseDao()).updateBatchCancel(idlist);
    }

	@Override
	public void lockById(int id) throws BusinessException {
		 ((TbSlLoanCreditDao)this.getBaseDao()).lockById(id);
		
	}

    @Override
    public List<TbSlLoanCreditLogForFront> queryTbSlLoanCreditLogForFront(int userIdOfIPayNowOfDebtor) throws BusinessException {
        return  ((TbSlLoanCreditDao)this.getBaseDao()).queryTbSlLoanCreditLogForFront(userIdOfIPayNowOfDebtor);
    }

    @Override
    public void lockTable() throws BusinessException {
        ((TbSlLoanCreditDao)this.getBaseDao()).lockTable();
    }

    @Override
    public List<TbSlNotPayBackCredit> queryCreditNotPayBackForSl(int userIdOfIPayNowOfDebtor) throws BusinessException {
        return   ((TbSlLoanCreditDao)this.getBaseDao()).queryCreditNotPayBackForSl(userIdOfIPayNowOfDebtor);
    }

    @Override
    public List<TbSlLoanCreditLog> queryNotPayBack() throws BusinessException {
        return ((TbSlLoanCreditDao)this.getBaseDao()).queryNotPayBack();
    }

    @Override
    public void cancelForPausedPlatform(Integer idOfPlatform) throws BusinessException {
        ((TbSlLoanCreditDao)this.getBaseDao()).cancelForPausedPlatform(idOfPlatform);
    }

    @Override
    public List<TbSlLoanCreditLog> queryWillExpire(Integer userIdOfJoinOfDebtor, Pageable page) throws BusinessException {
       List<TbSlLoanCreditLog> creditLogList=  ((TbSlLoanCreditDao)this.getBaseDao()).queryWillExpire(userIdOfJoinOfDebtor,TimeUtils.getCurDate(),page);
       if(!CommonUtils.isEmpty(creditLogList)){
             for(TbSlLoanCreditLog creditLog:creditLogList){
                 try{
                  String lastRefundTime=creditLog.getLastRefundTime();
                  String curDate=TimeUtils.getCurDate();
                  BigDecimal rate=new BigDecimal(0);
                 if(!CommonUtils.isEmpty(creditLog.getFee())){
                     rate=rate.add(new BigDecimal(creditLog.getFee()));
                 }
                 if(!CommonUtils.isEmpty(creditLog.getRate())){
                    rate=rate.add(new BigDecimal(creditLog.getRate()));
                 }
                 creditLog.setRate(rate.toString());
                 BigDecimal renewedrate=new BigDecimal("0");
                 if(!CommonUtils.isEmpty(creditLog.getRenewedFee())){
                     renewedrate= renewedrate.add(new BigDecimal(creditLog.getRenewedFee()));
                 }
                 if(!CommonUtils.isEmpty(creditLog.getRenewedRate())){
                     renewedrate= renewedrate.add(new BigDecimal(creditLog.getRenewedRate()));
                 }
                 creditLog.setRenewedRate(renewedrate.toString());
                      if(curDate.compareTo(lastRefundTime)<0){
                        long days=TimeUtils.getDateSpaceOfDay(creditLog.getRealLoanTime(),TimeUtils.getCurDate());
                        creditLog.setDays(new Long(days).toString());
                  }
                     if(curDate.compareTo(lastRefundTime)>0&&!CommonUtils.isEmpty(creditLog.getRenewedBeginTime())){
                           if(curDate.compareTo(creditLog.getRenewedRefundTime())<=0){
                               long days=TimeUtils.getDateSpaceOfDay(curDate,creditLog.getRenewedRefundTime());
                               creditLog.setDays(new Long(days).toString());
                           }
                     }
                 }catch (Exception e){
                     throw  new BusinessException("系统错误",e);
                 }
             }
       }
         return creditLogList;
    }

    @Override
    public List<TbSlStatusCreditLogVo> queryRenewedCredit(Integer userIdOfJoinOfCreditor,Integer userIdOfJoinOfDebtor,Integer idOfPlatform,String begintime,String endtime, Pageable page) throws BusinessException {
        return  ((TbSlLoanCreditDao)this.getBaseDao()).queryRenewedCredit(userIdOfJoinOfCreditor,userIdOfJoinOfDebtor,idOfPlatform,begintime,endtime, page);
    }

    @Override
    public List<TbSlLoanCreditLogVo> queryCreditForFloat(Map<String, Object> parammap, Pageable page) throws BusinessException {
        List<TbSlLoanCreditLogVo> list= ((TbSlLoanCreditDao)this.getBaseDao()).queryCreditForFloat(parammap,page);
        if(!CommonUtils.isEmpty(list)){
            for(TbSlLoanCreditLogVo vo:list){
                String  amountFloat=tbSlLoanFloatService.queryAmountByCreditId(vo.getId());
                vo.setAmountFloat(amountFloat);
            }
        }
        return list;

    }

    @Override
    public List<TbSlCreditLogForExcelVO> queryCreditForExcel(int joinid) throws BusinessException {
        List<TbSlCreditLogForExcelVO> list= ((TbSlLoanCreditDao)this.getBaseDao()).queryCreditForExcel(joinid);
        if(!CommonUtils.isEmpty(list)){
            for(TbSlCreditLogForExcelVO vo:list){
                BigDecimal fee=new BigDecimal(vo.getFee());
                BigDecimal rate=new BigDecimal(vo.getRate());
                rate=rate.add(fee);
                vo.setRate(rate.toString());
                BigDecimal renewedfee=new BigDecimal(vo.getRenewedFee());
                BigDecimal renewedrate=new BigDecimal(vo.getRenewedRate());
                renewedrate=renewedrate.add(renewedfee);
                vo.setRenewedRate(renewedrate.toString());
                
                vo.setAccountDelta(CommonUtils.getFenByString(vo.getAccountDelta()));
                vo.setTotalNotPaybackAmount(CommonUtils.getFenByString(vo.getTotalNotPaybackAmount()));
                vo.setTotalNotPaybackRate(CommonUtils.getFenByString(vo.getTotalNotPaybackRate()));
                vo.setTotalNotPaybackRenewedRate(CommonUtils.getFenByString(vo.getTotalNotPaybackRenewedRate()));
                vo.setTotalNotPaybackRenewedAmount(CommonUtils.getFenByString(vo.getTotalNotPaybackRenewedAmount()));
            }
        }
        return list;
    }

    @Override
    public List<TbSlLoanCreditLog> queryNotPayBackByPlatform(int platform) throws BusinessException {

        return  ((TbSlLoanCreditDao)this.getBaseDao()).queryNotPaybackByPlatform(platform);  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public TbSlStatusCreditLogVo queryStatusCreditLogVo(int id) throws BusinessException {
        return  ((TbSlLoanCreditDao)this.getBaseDao()).queryStatusCreditLogVo(id);
    }

    @Override
    public List<TbSlLoanCreditLog> queryCodeById(List<Integer> list) throws BusinessException {
        return ((TbSlLoanCreditDao)this.getBaseDao()).queryCreditByIdList(list);
    }

    @Override
    public List<TbSlLoanCreditLog> queryTsById(List<Integer> idlist) throws BusinessException {
        return  ((TbSlLoanCreditDao)this.getBaseDao()).queryTsById(idlist);
    }

    @Override
    public TbSlStatusCreditLogVo queryInfoById(Integer id) throws BusinessException {
        return ((TbSlLoanCreditDao)this.getBaseDao()).queryInfoById(id);
    }

    @Override
    public void updateCreditLogForBatch(Map<String, Object> map) throws BusinessException {
        ((TbSlLoanCreditDao)this.getBaseDao()).updateCreditLogForBatch(map);
    }

    @Override
    public void updateForCancelCredit(Integer processid) throws BusinessException {
        ((TbSlLoanCreditDao)this.getBaseDao()).updateForCancelCredit(processid);
    }

    @Override
    public void updateFileByProcessid(Integer process_info_id,String material) throws BusinessException {
        ((TbSlLoanCreditDao)this.getBaseDao()).batchUpateFileByProcessid(process_info_id,material);
    }

    @Override
    public List<TbSlStatusCreditLogVo> queryCreditByProcessid(Integer process_info_id) throws BusinessException {
        return  ((TbSlLoanCreditDao)this.getBaseDao()).queryCreditByProcessid(process_info_id);
    }

    @Override
    public void queryNeedMessage() throws BusinessException {
        if(CommonUtils.isDev())
        	return;
        
        List<TbSlLoanCreditLogVo> list=  ((TbSlLoanCreditDao)this.getBaseDao()).queryNeedMessage();
        if(CommonUtils.isEmpty(list))
        	return;
        
        for(TbSlLoanCreditLogVo vo:list){
            String mobile=vo.getMobile();
            String code=vo.getCode();
            if(CommonUtils.isEmpty(mobile))
            	return;
            
        	NotificationTemplate template = notificationTemplateService.findByName(ISLConstDef.LOAN_EXPIRE);
          	  if (template == null || StringUtils.isEmpty(template.getTemplate()))
          		  return;
          	String msg = template.getTemplate().replace("%code%", code);
            SMSSendUtil.sendMsg(mobile,msg);
        }
    }

    @Override
    public List<TbSlLoanCreditLogVo> queryWillExpireCreditForOperator(Pageable pageable) throws BusinessException {


        return   ((TbSlLoanCreditDao)this.getBaseDao()).queryWillExpireCreditForOperator(pageable);
    }

    @Override
    public List<SLLoanBillBaseInfoVo> querySlloanBillVo(String begintime, String endtime, Integer userIdOfJoinOfDebtor,Integer userIdOfJoinOfCreditor, Pageable pageable) throws BusinessException {

        List<SLLoanBillBaseInfoVo> billBaseInfoVos=((TbSlLoanCreditDao)this.getBaseDao()).queryLoanBillBaseInfoByTime(begintime, endtime, userIdOfJoinOfDebtor, userIdOfJoinOfCreditor, pageable);
        if(!CommonUtils.isEmpty(billBaseInfoVos)){
            for(SLLoanBillBaseInfoVo info:billBaseInfoVos){

                List<SlLoanBillDetailVo> billDetailVos=((TbSlLoanCreditDao)this.getBaseDao()).queryLoanBillDetailVo(begintime,endtime,info.getUserIdOfJoinOfDebtor());
               info.setDetailVoList(billDetailVos);
            }
        }
        return billBaseInfoVos;

    }

    @Override
    public SLLoanBillVo querySlLoanBillSumvo(String begintime, String endtime, Integer userIdOfJoinOfDebtor, Integer userIdOfJoinOfCreditor) throws BusinessException {

        return  ((TbSlLoanCreditDao)this.getBaseDao()).querySlLoanBillvo(begintime, endtime, userIdOfJoinOfDebtor, userIdOfJoinOfCreditor);
    }
}
